package com.xhwl.centiotdata.handler.alarm.impl;

import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.handler.alarm.AlarmFactory;
import com.xhwl.centiotdata.handler.alarm.AlarmHandler;
import com.xhwl.common.constant.cent.alarm.AlarmConstant;
import com.xhwl.common.dto.cent.alarm.iot.ElevatorDevice;
import com.xhwl.common.dto.cent.alarm.iot.IotAlarmBody;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.pojo.cent.alarm.AlarmManagement;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author Leon
 * @Description: TODO
 * @Date: 2022/3/22 17:31
 */
@Component
@Slf4j
public class AlarmHuaWeiIotDAElevatorDeviceHandler extends AlarmHandler {

    @Override
    public void afterPropertiesSet() throws Exception {
        AlarmFactory.register("ElevatorDevice", this);
    }

    @Override
    public void pushHuaWeiIotDAIotAlarmBody(IotAlarmBody t, DeviceDTO device) {
        ElevatorDevice elevatorDevice = JSONObject.parseObject(JSONObject.toJSONString(t.getProperties()), ElevatorDevice.class);
        List<Integer> binOneCount = getBinOneCount(Integer.valueOf(elevatorDevice.getZt()));
        if (binOneCount.contains(8)) {
            AlarmManagement alarmManagement = new AlarmManagement();
            alarmManagement.setAlarmTime(Date.from(t.getEvent_time().atZone(ZoneId.systemDefault()).toInstant()));
            alarmManagement.setDeviceId(device.getId());
            alarmManagement.setProjectId(device.getProjectId());
            alarmManagement.setAlarmInventoryCode("95392556");
            sendMq(AlarmConstant.JINMAO_TOPIC,alarmManagement);
        }
    }

    private List<Integer> getBinOneCount(int n) {
        List<Integer> result = new ArrayList<>();
        int index = 0;
        while (n > 0) {
            int x = n & 1 << index;
            if (x != 0) {
                result.add(index);
                n = n - (1 << index);
            }
            index++;
        }
        return result;
    }
}
